//
//  NetWorkManager.m
//  Copyright (c) 2015年 luo. All rights reserved.
//

#import "NetWorkManager.h"

@interface NetWorkManager ()<NSURLConnectionDataDelegate> {
    NSMutableData *_dataSource;
}

@property (nonatomic, copy) Block successBlock;
@property (nonatomic, copy) Block errorBlock;

@end

@implementation NetWorkManager

- (void)sendAsynWithURL:(NSString *)urlString
              parameter:(NSDictionary *)dictionary
                success:(Block)success
                  faild:(Block)faild {
    
    NSURL *url = [NSURL URLWithString:urlString];
    // 创建请求
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    // 设置内容部分
    [request setHTTPMethod:@"POST"];
    
    // 将字典拼接成字符串
    NSMutableString *string = [[NSMutableString alloc] init];
    for (NSString *key in dictionary) {
        [string appendFormat:@"%@=%@&",key,dictionary[key]];
    }
    // 转换成data
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    // 发送请求
    [NSURLConnection connectionWithRequest:request delegate:self];
    // 记录block
    self.successBlock = success;
    self.errorBlock = faild;
    
}

#pragma mark - NSURLConnectionDataDelegate

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
//    NSLog(@"收到数据");
    [_dataSource appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
//    NSLog(@"%@",[error localizedDescription]);
    self.errorBlock([error localizedDescription]);
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
//    NSLog(@"收到回复");
    _dataSource = [[NSMutableData alloc] init];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
//    NSLog(@"数据接收完成");
    id object = [NSJSONSerialization JSONObjectWithData:_dataSource options:NSJSONReadingMutableLeaves error:nil];
    // 执行block
    _successBlock(object);
}

@end
